<!-- 商品属性页面 -->
<script setup lang="ts">
import CategoryView from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
let CategoryStore = useCategoryStore()
let attrArr = ref<Attr[]>([])
//卡片的场景
let sence = ref(0)
// 新增属性值的存储
let attrParams = reactive<Attr>({
  attrName: '', //新增三级分类
  attrValueList: [], //新增属性数组
  categoryId: '', //三级分类id
  categoryLevel: 3, //三级分类
})
//收集input框实例
let inputArr: any = ref([])
//添加属性
const addAttr = () => {
  //在添加属性前清空收集到的数据
  Object.assign(attrParams, {
    attrName: '', //新增三级分类
    attrValueList: [], //新增属性数组
    categoryId: CategoryStore.c3Id, //三级分类id
    categoryLevel: 3, //三级分类
  })
  sence.value = 1 //显示添加属性的场景
}
//修改属性
const updatedAttr = (row: Attr) => {
  sence.value = 1
  //将已有的属性对象赋值给
  Object.assign(attrParams, JSON.parse(JSON.stringify(row))) //assigin 是浅拷贝，两个指向的是同一个对象，无论哪一方发送变化都会变化
}
//取消的事件
const cancel = () => {
  sence.value = 0
}
// 添加属性值的方法
const addAttrValue = () => {
  // console.log('添加属性值')，就需要添加属性值
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //展示和编辑属性场景的标识
  })
  // 添加属性值之后自动聚焦到最后一个属性框上
  nextTick(() => {
    inputArr.value[inputArr.value.length - 1].focus()
  })
}
//删除属性操作
const deleteAttr = async (attrId: number) => {
  let res: any = await reqRemoveAttr(attrId)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 展示和编辑属性的切换事件
const switchEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  //使用nextTick等待响应式数据变化之后再更新组件实例
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
const switchLook = (row: AttrValue, $index: number) => {
  //在这之前判断添加属性值的一些非法情况： 属性值为空， 属性值重复
  if (row.valueName.trim() == '') {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  //查找重复元素
  let repeat = attrParams.attrValueList.find((item) => {
    //把自身排除，不要和自己对比
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }

  row.flag = false
}

//监听三级分类的变化
watch(
  () => CategoryStore.c3Id,
  () => {
    // 变化时先把attrArr的内容清空
    attrArr.value = []
    //三级分类存在才发请求
    if (CategoryStore.c3Id) {
      getAttr()
    }
  },
)

const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = CategoryStore
  // console.log(c1Id, c2Id, c3Id)
  const res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (res.code === 200) {
    attrArr.value = res.data
  }
  // console.log('res是', res)
}
//添加属性值之后的保存
const save = async () => {
  //将收集到属性信息发送请求以保存
  let res = await reqAddOrUpdateAttr(attrParams)
  // console.log(res)
  if (res.code == 200) {
    sence.value = 0

    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
//在组件实例销毁之前将仓库中存储的当前页面的数据清空
onBeforeUnmount(() => {
  // console.log(CategoryStore)
  CategoryStore.$reset()
})
</script>

<template>
  <div>
    <CategoryView :scene="sence" />
    <el-card style="margin: 10px 0">
      <div v-show="sence == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          style="margin: 10px 0"
          :disabled="CategoryStore.c3Id ? false : true"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table border style="10px 0" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="60px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                v-for="item in row.attrValueList"
                :key="item.id"
                style="margin: 5px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row, $index }">
              <el-button
                size="small"
                icon="Edit"
                @click="updatedAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除${row.attrName}？`"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 编辑页 -->
      <div v-show="sence == 1">
        <el-form>
          <el-form-item label="属性名称">
            <el-input
              placeholder="请你输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-table
          border
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                placeholder="请输入属性值的名称"
                v-model="row.valueName"
                v-if="row.flag"
                :ref="(vc: any) => (inputArr[$index] = vc)"
                @blur="switchLook(row, $index)"
              ></el-input>
              <div v-else @click="switchEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped></style>
